package com.smart.job;

import com.smart.pojo.ConceptualProduct;
import com.smart.pojo.Finance;
import com.smart.pojo.Produce;
import com.smart.pojo.Product;
import com.smart.service.IConceptualProductService;
import com.smart.service.IFinanceService;
import com.smart.service.IProduceService;
import com.smart.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

@Component
public class ProduceJob {

    @Autowired
    private IProduceService produceService;

    @Autowired
    private IProductService productService;

    @Autowired
    IFinanceService financeService;

    @Autowired
    IConceptualProductService conceptualProductService;

    //cron表达式 秒 分 时 天 月
    @Scheduled(cron = "0 0 23 * * ?") //每天晚上11点触发
//    @Scheduled(cron = "0/5 * * * * ?")  //每五秒
//    @Scheduled(cron = "0 0/1 * * * ?")  //每1分钟
    public void produce() {
        System.out.println("执行生产任务，更新库存");
        //记录生产财务
        Finance finance = new Finance();
        finance.setType(2);
        finance.setAmount(new BigDecimal(0));
        List<Produce> produceList = produceService.lambdaQuery()
                .eq(Produce::getStatus, 1)
                .list();
        for (Produce produce : produceList) {
            Product product = productService.getById(produce.getProductId());
            if (product != null) {
                product.setNum(product.getNum() + produce.getQuantity());
                productService.updateById(product);

                //计算生产成本
                ConceptualProduct byId = conceptualProductService.getById(product.getConceptualId());
                finance.setAmount(finance.getAmount().add(byId.getProductionCosts().multiply(new BigDecimal(produce.getQuantity()))));
            }
        }
        financeService.save(finance);
    }
}
